package com.atguigu.srb.core.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import java.time.Duration;

@Configuration
@EnableCaching  // 1. 开启缓存管理
public class RedisConfig {
    //  组件的定制化-->@PostConstruct 对组件进行初始化设置(修改属性)  --> @PostConstruct
    @Autowired
    RedisTemplate redisTemplate;

    //当前类对象初始化后 给装配的RedisTemplate配置键和值的序列化器
    @PostConstruct//注解的方法会在Bean的属性被容器设置之后，且Bean被初始化之前被调用
    public void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    //创建缓存管理器对象添加到容器中
    @Bean
    //只要引入了commons-pool2依赖,项目启动时会自动初始化redis连接工厂
    public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory){

        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()//设置默认配置
                .entryTtl(Duration.ofMinutes(600))//设置过期时间
//                .disableCachingNullValues(); // 禁止缓存空数据
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer())) //设置键的序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));//设置值的序列化器

        //创建缓存管理器对象
        return RedisCacheManager
                .builder(lettuceConnectionFactory)  //配置redis连接工厂
                .cacheDefaults(config)//缓存管理器 管理缓存的配置(键值序列化器、缓存过期时间、空值是否缓存)
                .build();
    }
}